<template>
  <div class="order-page-container">
    <!-- 页面头部，使用Element UI的Card组件包裹，增加样式层次感 -->
    <van-nav-bar
      title="我的订单"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      bind:click-left="onClickLeft"
    />
    <!-- 订单状态筛选栏，使用Element UI的Radio Group组件 -->
    <el-radio-group v-model="selectedStatus" @change="filterOrders">
      <el-radio-button label="全部">全部</el-radio-button>
      <el-radio-button label="待支付">待支付</el-radio-button>
      <el-radio-button label="待发货">待发货</el-radio-button>
      <el-radio-button label="待收货">待收货</el-radio-button>
      <el-radio-button label="已完成">已完成</el-radio-button>
      <el-radio-button label="已取消">已取消</el-radio-button>
    </el-radio-group>
    <!-- 订单列表展示，使用Vant的List组件实现滚动加载等功能 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多订单了"
      @load="onLoad"
    >
      <van-cell
        v-for="(order, index) in displayedOrders"
        :key="index"
        :title="`订单编号：${order.orderId}`"
        :label="`下单时间：${order.createTime}`"
      >
        <template #default>
          <div class="order-content"      @click="onClickRight(order)">
            <br>
            <div class="order-product-info" >
              <van-image :src="order.image" fit="contain" width="50" height="50"/>

              <span class="product-names">{{ getProductNames(order.products) }}</span>
            </div>
            <div>
              <span class="order-total-price">商品名称：{{ order.name }}</span>
            </div>
            <div class="order-status">{{ order.status }}</div>
          </div>
        </template>
        <template #right-icon>
          <div class="order-actions">
            <van-button v-if="order.status === '待支付'" type="danger" size="mini" @click="cancelOrder(order)">
              取消订单
            </van-button>
            <van-button v-if="order.status === '待支付'" type="primary" size="mini" @click="goToPay(order)">去支付
            </van-button>
            <van-button v-if="order.status === '待发货'" type="default" size="mini" disabled>待发货</van-button>
<!--            <van-button v-if="order.status === '待收货'" type="primary" size="mini" @click="checkLogistics(order)">-->
<!--              查看物流-->
<!--            </van-button>-->
            <van-button v-if="order.status === '待收货'" type="success" size="mini" @click="confirmReceipt(order)">
              确认收货
            </van-button>
            <van-button v-if="order.status === '已完成'" type="default" size="mini" disabled>已完成</van-button>
            <van-button v-if="order.status === '已取消'" type="default" size="mini" disabled>已取消</van-button>
          </div>
        </template>
      </van-cell>
    </van-list>
  </div>
</template>

<script>
import axios from "axios";
import {Dialog, Toast} from "vant";

export default {
  data() {
    return {
      userId: null,
      allOrders: [],
      selectedStatus: '全部',
      displayedOrders: [],
      loading: false,
      finished: false,
      findId: ''
    };
  },
  methods: {
    onClickRight(order){
      // 查看物流的具体逻辑，请求物流信息展示等
      console.log("获取到的订单id为：" + order.orderId)
      localStorage.setItem("orderId",order.orderId)
      this.$router.push('/orderShow')
    },
    onClickLeft() {
      Toast('返回');
      //返回上一个页面
      this.$router.push('myShow');
    },
    findAllOrders() {
      console.log("uid=" + this.userId)
      axios.post('/orders/orders/findAll').then(res => {
        //打印接口返回数据
        const a = res.data;
        const rawData = a.filter(item => item.userId === this.userId);
        // 将接口返回的数据映射到期望的格式
        this.allOrders = rawData.map(order => ({
          orderId: order.orderId,
          name: order.name,
          createTime: order.createTime,
          image: order.image,
          products: [{}],
          status: this.getStatusLabel(order.status) // 将状态码转换为状态标签
        }));
        console.log("转换后的数据");
        console.log(this.allOrders);
        this.filterOrders();
      });
    },
    getStatusLabel(statusCode) {
      const statusMap = {
        1: '待支付',
        2: '待发货',
        3: '待收货',
        4: '已完成',
        5: '已取消'
      };
      return statusMap[statusCode] || '未知状态';
    },
    filterOrders() {
      this.displayedOrders = [];
      this.finished = false;
      this.loading = false;
      if (this.selectedStatus === '全部') {
        this.displayedOrders = this.allOrders;
        this.finished = true;
      } else {
        this.allOrders.forEach(order => {
          if (order.status === this.selectedStatus) {
            this.displayedOrders.push(order);
          }
        });
      }
    },
    onLoad() {
      // 模拟加载更多订单，这里可以实际请求接口获取更多数据
      setTimeout(() => {
        this.loading = false;
        if (this.displayedOrders.length >= this.allOrders.length) {
          this.finished = true;
        }
      }, 1000);
    },
    getProductNames(products) {
      return products.map(product => product.name).join('、');
    },
    cancelOrder(order) {
      // 取消订单的具体逻辑，比如发送请求到后端等
      console.log(`取消订单：${order.orderId}`);
      this.findId = order.orderId;
      console.log("findId=" + this.findId);
      // 使用 Dialog 确认对话框
      Dialog.confirm({
        title: '确认取消订单',
        message: `确定要取消订单 ${order.orderId} 吗？`,
      }).then(() => {
        // 用户点击确认按钮
        axios.post(`/orders/orders/removeOrder?findId=${this.findId}`).then(res => {
          this.$message.success(res.data.message);
          this.findAllOrders();
        }).catch(error => {
          this.$message.error('取消订单失败，请稍后再试');
          console.error(error);
        });
      }).catch(() => {
        // 用户点击取消按钮
        Toast('取消操作已取消')
      });
    },
    // -------------------------跳转商品支付页面-------------------------
    goToPay(order) {
      console.log("获取到的订单信息为：" + order.orderId)
      this.findId = order.orderId
      console.log("findId=" + this.findId)
      axios.get(`/orders/orders/findByOrderId?findId=${this.findId}`).then(res => {
        console.log(res.data.data.orders)
        localStorage.setItem("orderId", JSON.stringify(res.data.data.orders.orderId))
        this.$router.push('/orderSubmit02')
      })
    },
    checkLogistics(order) {
      // 查看物流的具体逻辑，请求物流信息展示等
      console.log(`查看订单${order.orderId}的物流信息`);
    },
    //确认收货
    confirmReceipt(order) {
      // 确认收货的具体逻辑，通知后端等
      this.findId = order.orderId
      console.log("findId=" + this.findId)
      axios.post(`/orders/orders/confirmReceipt?findId=${this.findId}`).then(res=>{
        this.$message.success(res.data.message)
        this.findAllOrders();
      })
    }
  },
  created() {
    const user = localStorage.getItem("user");
    if (user) {
      this.user = JSON.parse(user);
      this.userId = this.user.id;
      // alert(this.userId);
    }
    this.findAllOrders();
  }
};
</script>

<style scoped>

</style>
